/*************************************************************************************************
 * @file       main.c
 * @author     BLE Group
 * @brief 
 * @version    1.0.1
 * @date       2025-03-08
 * 
 * @copyright Copyright (c) 2024, CHIP PUMP Microelectronics.
                 All rights reserved.
 * 
 ************************************************************************************************/
#include "include.h"
#include "hal_clock.h"
#include "api_rf_2g4.h"
#include "log_dbg.h"
#include "glh_app_process.h"
#include "ble_viot.h"
#include "glh_sys_tick.h"
#include "glh_pwm.h"

str_ble_viot_para opcode_para;	//解密后数据

extern void RemoteReceiveCallback(str_ble_viot_para sReceiveData);

enum en_adv_pdu_type
{

	/******BLE VIOT******/
	BLE_VIOT_ADV		= 0x30,
	
	/********MESH********/
	MESH_PB_ADV			= 0x29,
	MESH_BEACON			= 0x2B,
	MESH_MESSAGE		= 0x2A,
	ALI_MESH_ADV		= 0x40,
	ALI_APP_IOS_V12_ADV = 0x41,
	ALI_APP_IOS_ADV 	= 0x44,
};

uint8_t get_adv_type(uint8_t* ble_payload, uint8_t payload_lenth)
{
	uint8_t* adv_data = ble_payload + 8;//get adv data from buffer,the input ble_payload is start from header
	uint8_t adv_data_len = payload_lenth - 8;
	
	//check is ble v1 packet?
	if(0x00 == is_ble_viot_pdu(adv_data,adv_data_len))
	{
		return BLE_VIOT_ADV;
	}
	return 0x0;
}

uint8_t ble_viot_unpack_handler(uint8_t* ble_payload, uint8_t payload_lenth)
{
	uint8_t ret = 0x0;		//解密后状态

//    str_ble_viot_para opcode_para;	//解密后数据
    
    ret = ble_viot_decoder( ble_payload, payload_lenth, &opcode_para);

	return ret;
}

static uint8 iRemotorDataFitle(uint8 *pData, uint8 u8DataLen)
{
    uint8 adv_type = 0; 
	uint8_t*	adv_data = NULL;
	uint8_t		adv_data_len;
    
    if(u8DataLen > 39)
    {
        return 0;
    }
    
    adv_type = get_adv_type(pData, u8DataLen);
    if(adv_type != BLE_VIOT_ADV)
    {
        return 0;
    }

	adv_data = pData + 8;
	adv_data_len = u8DataLen - 8;    
    if(ble_viot_unpack_handler(adv_data,adv_data_len) != BLE_VIOT_SUCCESS)
    {
        return 0;
    }
    
    return 1;
}

__RAM_CODE_SECTION void rf_2g4_rx_handler(uint8_t *rx_data ,uint8_t rx_len)
{
	if(iRemotorDataFitle(rx_data, rx_len) == 0)
    {
        return;
    }
    RemoteReceiveCallback(opcode_para);
}

uint8 au8Ch[3] ={RF_CH37, RF_CH38, RF_CH39};

int main(void)
{
	static uint32 s_u32LastChangeChTime = 0;
	static uint8 s_u8ChIndex = 0;

	JTAPS_Init();
	rf_2g4_init();
	rf_2g4_set_tx_power(0);
	rf_2g4_rx_data(rf_2g4_rx_data_buf,MAX_RF_LENGTH,RF_CH37);
	rf_2g4_rx_start(RF_CH37);
	
	while(1)
	{
		if(GulSystickCount - s_u32LastChangeChTime >= 7)
		{
			s_u32LastChangeChTime = GulSystickCount;
			
			s_u8ChIndex++;
			if(s_u8ChIndex >= 3)
			{
				s_u8ChIndex = 0;
			}
		}
		
		WDT_FEED();
		rf_2g4_rx_start(au8Ch[s_u8ChIndex]);
		JTAPS_MainThread();
	}
	
	return 0;
}

